
//
//  PreferenceViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import Networking
import Alamofire
import PKHUD
import SwiftyJSON

class PreferenceViewController: BaseViewController, UICollectionViewDelegate, UICollectionViewDataSource, AddCornerUIRectCorner, BottomShadow {
    
    @IBOutlet weak var mainView: UIView!
    @IBOutlet weak var tipView: UIView!
    @IBOutlet weak var mainCollectionView: UICollectionView!
    @IBOutlet weak var doneButton: UIButton!
    var trees: [treeModel] = []
    struct SelectData {
        var selectData: [Bool] = []
        init(names: [String]) {
            selectData = names.map({value -> Bool in
                return false
            })
        }
    }
    
    typealias select = (_ arr: [String]) -> Void
    var sele: select?
    private let superMargin: CGFloat = 10
    private let RoundMargin: CGFloat = 20
    private let itemMargin: CGFloat =  15
    private let itemCount: CGFloat = 3
    private let itemHeght: CGFloat = 50
    private var datas: SelectData?
    private let itemImageNames = [("btn_ar_pr", "AR"), ("btn_game_pr", "游戏"), ("btn_music_pr", "音乐"), ("btn_shopping_pr", "购物"), ("btn_life_pr", "宅家里"), ("btn_movie_pr", "电影"), ("btn_pet_pr", "宠物"), ("btn_work_pr", "工作"), ("btn_aliens_pr", "外星人")]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        // Do any additional setup after loading the view.
    }
    
    func setUI() {
        titleLabel(text: "设置偏好", nil)
        setShadow(view: mainView, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)
        addCornerWithView(aView: doneButton, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        mainCollectionView.register(UINib(nibName: "\(PreferenceCollectionViewCell.self)", bundle: nil), forCellWithReuseIdentifier: "\(PreferenceCollectionViewCell.self)")
        datas = SelectData(names: itemImageNames.flatMap({$0.0}))
        let layout = UICollectionViewFlowLayout()
        let itemWidth = (ScreenWidth - RoundMargin * 2 - (itemCount - 1) * itemMargin - superMargin * 2) / itemCount
        layout.itemSize = CGSize(width: itemWidth, height: itemHeght)
        layout.minimumInteritemSpacing = itemMargin
        layout.minimumLineSpacing = itemMargin
        layout.sectionInset = UIEdgeInsetsMake(0, RoundMargin, 0, RoundMargin)
        mainCollectionView.collectionViewLayout = layout
        mainCollectionView.delegate = self
        mainCollectionView.dataSource = self
        mainCollectionView.reloadData()
        fetchTree()
    }
    
    override func setNavigation() {
    }
    
    // MARK:- UICollectionViewDataSource
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
       return trees.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "\(PreferenceCollectionViewCell.self)", for: indexPath) as? PreferenceCollectionViewCell
        cell?.layer.contents = UIImage(named: "bg_preference")?.cgImage
        cell?.layer.cornerRadius = CORNERRADIUS * 2
        cell?.layer.masksToBounds = true
        cell?.selectImageView.image = UIImage(named: "btn_preference_unSelect")
        cell?.selectImageView.highlightedImage = UIImage(named: "btn_preference_select")
        let tree = trees[indexPath.row]
        cell?.showData(tree: tree)
        return cell!
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var model = trees[indexPath.item]
        var json = JSON(model.selected).boolValue
        json = !json
        if json {
            model.selected = "1"
        }else{
            model.selected = "0"
        }
        trees[indexPath.item] = model
      
        collectionView.reloadData()
    }
    
    @IBAction func doneAct(_ sender: Any) {
        var arr: [String] = []
        for item in trees {
            if item.selected == "1"{
                arr.append(item.id!)
            }
        }
        self.sele!(arr)
    }
    
    func fetchTree() -> Void {
        var requesturl = "\(BaseURL)\(interestMarkUrl)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        
                                         let arr = json["data"].array!
                                        
                                        for subject in arr{
                                            let dic = subject.dictionary!
                                              var model = treeModel(fromDic: dic)
                                            self.trees.append(model)
                                            }
                                        
                                        self.mainCollectionView.reloadData()
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
                            
        }
    }
}
